from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

# 打开Chrome浏览器
driver = webdriver.Chrome()

# 导航到注册页面
driver.get("https://demoqa.com/automation-practice-form")

# 输入无效的数据并验证错误消息
first_name_input = driver.find_element(By.ID, "firstName")
first_name_input.send_keys("123")
first_name_input.send_keys(Keys.TAB)  # 将焦点从文本框移开
last_name_input = driver.find_element(By.ID, "lastName")
last_name_input.send_keys("456")
last_name_input.send_keys(Keys.TAB)  # 将焦点从文本框移开
email_input = driver.find_element(By.ID, "userEmail")
email_input.send_keys("invalidemail")
email_input.send_keys(Keys.TAB)  # 将焦点从文本框移开
gender_radio = driver.find_element(By.CLASS_NAME, "custom-control-label")
gender_radio.click()
phone_number = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, "userNumber")))
phone_number.send_keys("1234567890")
submit_button = driver.find_element(By.ID, "submit")
ActionChains(driver).move_to_element(submit_button).perform()
# # Wait for the submit button to be clickable
# WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "submit")))

submit_button.click()

error_messages = driver.find_elements(By.CSS_SELECTOR, ".form-control.is-invalid, .was-validated .form-control:invalid")
# assert len(error_messages) == 2
# assert "Invalid email" in error_messages[0].text
# assert "10 digit mobile number" in error_messages[1].text
if len(error_messages) > 0:
    print("输入信息有误")

# 输入有效的数据并验证成功消息
first_name_input = driver.find_element(By.ID, "firstName")
first_name_input.clear()
first_name_input.send_keys("John")
last_name_input = driver.find_element(By.ID, "lastName")
last_name_input.clear()
last_name_input.send_keys("Doe")
email_input = driver.find_element(By.ID, "userEmail")
email_input.clear()
email_input.send_keys("johndoe@example.com")
gender_radio = driver.find_element(By.CLASS_NAME, "custom-control-label")
gender_radio.click()
phone_input = driver.find_element(By.ID, "userNumber")
phone_input.clear()
phone_input.send_keys("1234567890")
submit_button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "submit")))
submit_button.click()

success_message = driver.find_element(By.CLASS_NAME, "modal-header")
# assert "Thanks for submitting the form" in success_message.text
if "Thanks for submitting the form" in success_message.text:
    print("更改输入信息成功，输入结果正确")

# 关闭浏览器
driver.quit()
